package com.fattyCorps.config;

import com.fattyCorps.an.AMsgType;
import com.fattyCorps.cache.PlayerMsgPipeMgr;
import com.fattyCorps.obj.msg.HttpStatus;
import com.fattyCorps.service.GlobalService;
import com.fattyCorps.utils.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class CustomInterceptor implements HandlerInterceptor {

    @Autowired
    GlobalService globalService;
    @Autowired
    PlayerMsgPipeMgr playerMsgPipeMgr;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (globalService.serverState.equals(GlobalService.SERVER_STATE.CLOSED)) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");

            JSONObject retJson = new JSONObject();
            retJson.put("code", HttpStatus.SERVER_CLOSE.getCode());
            retJson.put("msg", HttpStatus.SERVER_CLOSE.getMsg());
            PrintWriter writer = response.getWriter();
            writer.append(retJson.toString());
            return false;
        }

        if (handler instanceof HandlerMethod) {
            HandlerMethod hm = (HandlerMethod) handler;
            AMsgType methodAnnotation = hm.getMethodAnnotation(AMsgType.class);
            // 若方法非只进行读取操作则加锁防止并发问题
            if (methodAnnotation == null || !methodAnnotation.readOnly()) {
                Integer playerId = ServletUtils.getPlayerIdByRequest(request, false);
                if (playerId > 0) {
                    playerMsgPipeMgr.before(playerId);
                }
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod hm = (HandlerMethod) handler;
            AMsgType methodAnnotation = hm.getMethodAnnotation(AMsgType.class);
            if (methodAnnotation == null || !methodAnnotation.readOnly()) {
                Integer playerId = ServletUtils.getPlayerIdByRequest(request, false);
                if (playerId > 0) {
                    playerMsgPipeMgr.after(playerId);
                }
            }
        }
    }

}
